package org.joinme.backend.config;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "org.joinme.backend.mapper")
public class MyBatisConfig {
    @Bean
    @Profile("prod")
    public PooledDataSource prodDataSource(){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://47.100.225.39:3306/joinme?useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("joinme2018");
        //ping确保连接还在正常工作
        dataSource.setPoolPingEnabled(true);
        dataSource.setPoolPingQuery("select * from joinme.Juser limit 1");
        dataSource.setPoolPingConnectionsNotUsedFor(3600000);

        dataSource.setPoolMaximumActiveConnections(2000);
        dataSource.setPoolMaximumIdleConnections(5);

        return dataSource;
    }

    @Bean
    @Profile("prod")
    public DataSourceTransactionManager prodTransactionManager() {
        return new DataSourceTransactionManager(prodDataSource());
    }

    @Bean
    @Profile("prod")
    public SqlSessionFactoryBean prodSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(prodDataSource());
        sessionFactory.setTypeAliasesPackage("org.joinme.backend.mapper");
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
        sessionFactory.setTypeHandlersPackage("org.joinme.backend.util");//具体作用是啥？
        return sessionFactory;
    }
}
